<?php
namespace app\admin\model;

use think\Model;

class Chanpin extends Model
{
    //关闭时间戳
    //protected $autoWriteTimestamp = false;

    /**
     * 显示列表
     * @return array
     */
    public function _list()
    {
        $list = $this->order('sort_order desc')->select();
        return $list;
    }

    /**
     * 模型数据验证
     * @param $data
     * @return bool|string
     */
    public function data_verify($data)
    {
        //$Category = new Category();
        $update = isset($data['id']) ? ['id' => $data['id']] : []; //是否更新操作
        $result = $this->validate(
            [
                'thumb_url' => 'require|max:500',
                'title' => 'require|max:255',
            ],
            [
                'thumb_url.require' => '图片地址不能为空',
                'title.require' => '新闻标题不能为空',
                'thumb_url.max' => ' 图片地址长度不能超过255个字符 ',
                'title.max' => ' 新闻标题长度不能超过255个字符 ',
            ]
        )->allowField(true)->save($data, $update);
        if(false === $result){
            //  验证失败 输出错误信息
            $error = $this->getError();
            if (is_array($error)) {
                return $error[key($error)];
            }else {
                return $error;
            }
        }
        return true;
    }

    /**
     * 分页
     */
    public function pageQuery(){
        return $this->order('sort_order desc')->order('id desc')->paginate('10');
    }

    /**
     * 获取指定对象
     */
    public function getById($id){
        $single = $this->where(['id'=>$id,'dataFlag'=>1])->find();
        $singlec = Db::name('article_cats')->where(['catId'=>$single['catId'],'dataFlag'=>1])->field('catName')->find();
        $single['catName']=$singlec['catName'];
        $single['articleContent'] = htmlspecialchars_decode($single['articleContent']);
        return $single;
    }

    /**
     * 删除
     */
    public function del($id){
        if (!$id || !is_int($id)) return false;
        $result = $this->get($id);
        //$result = Category::get($id);
        if(false !== $result){
            if ( $result->delete() ) {
                return true;
            }else {
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 批量删除
     */
    public function delByBatch(){
        $ids = input('post.ids');
        $data = [];
        $data['dataFlag'] = -1;
        $result = $this->where(['id'=>['in',$ids]])->update($data);
        if(false !== $result){
            return WSTReturn("删除成功", 1);
        }else{
            return WSTReturn($this->getError(),-1);
        }
    }
}